<?php	
	abstract class BuildCounter {
		public static $revision;
					  
		public static function captureAllDirs(Dir $d){
			$dirs = array();
			foreach($d->listDirectories() as $d2){
				$dirs[] = $d2;
				$dirs = array_merge($dirs, self::captureAllDirs($d2));
			}
			
			return $dirs;
		}
		
		public static function stateRevision(){
			echo PHP_EOL . '<!-- Revision ' . self::$revision . ' -->';
		}
	}
	
	$extensions = array('php', 'phps', 'php5', 'php4');
	
	$dd = new DataDirectory('nimp-buildutils');
	$ini = $dd->restore('build-counter');
	
	BuildCounter::$revision = (int) $ini['revision'];
	
	$dir = new Dir(PATH_CORE);
	$previous = isset($ini['files']) ? $ini['files']->getArrayCopy() : array();
	$current = array();
	foreach(BuildCounter::captureAllDirs($dir) as $d){
		foreach($d->listFiles() as $f){
			if(in_array($f->getExtension(), $extensions)) $current[$f->getAbsolutePath()] = $f->getModificationTime();
		}
	}
	
	foreach($dir->listFiles() as $f){
		if(in_array($f->getExtension(), $extensions)) $current[$f->getAbsolutePath()] = $f->getModificationTime();
	}
	
	if(count(array_diff($current, $previous)) > 0){
		BuildCounter::$revision++;
		$newIni = array('revision' => BuildCounter::$revision,
						'files' => $current);
		$transformer = new IniParser($newIni);
		$dd->store('build-counter', $transformer);
		
		/*$zip = new ZipArchive();
		$zip->open(dirname(NIMP_BC_FILE) . DS . 'r' . BuildCounter::$revision . '-' . date('Y-m-d') . '.zip', ZipArchive::CREATE);
		
		foreach($current as $f => $m){
			if(substr($f, 0, strlen(PATH_CORE)) == PATH_CORE){
				$l = trim(substr($f, strlen(PATH_CORE)), DS);
				$zip->addFile($f, $l);
			}
		}
		
		$zip->close();*/
		
		unset($transformer);
		unset($newIni);
	}

	register_shutdown_function('BuildCounter::stateRevision');
	
	unset($dir);
	unset($previous);
	unset($current);
	unset($ini);
	unset($dd);
	unset($extensions);
	unset($d);
	unset($f);
?>